package com.chansos.dubbogo.ui;

import com.chansos.dubbogo.common.Registry;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBRadioButton;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class RegistriesGroup extends JBPanel<RegistriesGroup> {
    ButtonGroup registries = new ButtonGroup();

    List<JBRadioButton> options = new ArrayList<>() {{
        for (Registry value : Registry.values()) {
            JBRadioButton jbRadioButton = new JBRadioButton(value.getName(), value.isSelected());
            jbRadioButton.setToolTipText(value.getAlias());
            add(jbRadioButton);
        }
    }};

    public RegistriesGroup() {
        super(new FlowLayout(FlowLayout.LEFT));
        JBLabel label = new JBLabel("Registry: ");
        label.setPreferredSize(new Dimension(100, (int) label.getPreferredSize().getHeight()));
        add(label);

        Box box = Box.createVerticalBox();
        JBPanel<?> panel = new JBPanel<>(new FlowLayout(FlowLayout.LEFT));
        for (JBRadioButton option : options) {
            registries.add(option);
            panel.add(option);
        }
        box.add(panel);
        add(box);
    }

    public void clear() {
        for (JBRadioButton option : options) {
            option.setSelected(false);
        }
    }

    public Registry getSelection() {
        String name = null;
        try {
            Optional<JBRadioButton> option = options.stream().filter(AbstractButton::isSelected).findFirst();
            if (option.isPresent()) {
                name = option.get().getName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Registry.parse(name);
    }
}
